package com.taotao.tools.enums.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.taotao.tools.core.str.StringUtil;
import com.taotao.tools.enums.BaseEnum;
import com.taotao.tools.enums.annotation.EnumField;
import com.taotao.tools.enums.constant.EnumConstant;
import com.taotao.tools.enums.utils.BaseEnumUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Collection;


/**
 * BaseEnum枚举序列化转化；XXX_label字段表示枚举的名称,XXX_code表示枚举的编码
 * <pre>
 *     1. 字段是普通类型，则追加一个_label后缀字段。
 *     2. 字段是 BaseEnum 则追加一个_label后缀字段和一个_code后缀字段
 *     3. 字段是 分隔符分隔字符串，则追加一个_label后缀字段
 *     4. 字段是 BaseEnum[] 或Collection<BaseEnum>则追加一个_label后缀字段和一个_code后缀字段
 *     5. 字段是普通数组或普通Collection则追加一个_label后缀字段
 * </pre>
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class EnumAtSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    private String fieldName;

    private Class<?> fieldClass;
    private EnumField enumAt;

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException {

        if (null == value) {
            return;
        }

        if (fieldClass.isArray() || value instanceof Collection) {
            //4,5 数组集合处理
            writeDefaultEnumArr(jgen, value);
            writeLable(jgen, value);
            writeCode(jgen, value);

        } else {
            if (StringUtil.isBlank(enumAt.separator())) {
                // 1,2
                writeSingleField(jgen, value);
            } else {
                //3 分隔符分隔情况
                if (value instanceof String) {
                    String s = (String) value;
                    if (StringUtil.isBlank(s)) {
                        return;
                    }

                    jgen.writeObject(value);
                    writeSeparatorLable(jgen, s.split(enumAt.separator()));
                } else {
                    throw new IllegalStateException("分隔符不能用于非String");
                }
            }
        }
    }

    private void writeSingleField(JsonGenerator jgen, Object value) throws IOException { //写原始值
        jgen.writeObject(value);
        if (value instanceof BaseEnum) {
            jgen.writeObjectField(fieldName + EnumConstant.CODE_FIELD_SUFFIX, ((BaseEnum<?>) value).getCode());
            jgen.writeObjectField(fieldName + EnumConstant.LABEL_FIELD_SUFFIX, ((BaseEnum<?>) value).getText());
        } else {
            // 写对象中不存在的属性
            jgen.writeObjectField(fieldName + EnumConstant.LABEL_FIELD_SUFFIX, getFieldEnumText(enumAt, value));
        }

    }

    private void writeSeparatorLable(JsonGenerator jgen, String[] value) throws IOException {
        jgen.writeFieldName(fieldName + EnumConstant.LABEL_FIELD_SUFFIX);
        jgen.writeStartArray();
        StringBuilder s = new StringBuilder();
        for (String v : value) {
            BaseEnum e = BaseEnumUtils.getByCodeStr(enumAt.value(), v);
            s.append(e.getText()).append(",");
        }

        jgen.writeString(s.substring(0, s.length() - 1));
        jgen.writeEndArray();
    }

    private void writeLable(JsonGenerator jgen, Object value) throws IOException {
        jgen.writeFieldName(fieldName + EnumConstant.LABEL_FIELD_SUFFIX);
        if (fieldClass.isArray()) {
            jgen.writeStartArray();
            for (Object v : (Object[]) value) {
                if (v instanceof BaseEnum) {
                    jgen.writeObject(((BaseEnum<?>) v).getText());
                } else {
                    BaseEnum e = BaseEnumUtils.getByCode(enumAt.value(), v);
                    jgen.writeObject(e.getText());
                }

            }
            jgen.writeEndArray();
        }

        if (value instanceof Collection) {
            jgen.writeStartArray();
            for (Object v : (Collection) value) {
                if (v instanceof BaseEnum) {
                    jgen.writeObject(((BaseEnum<?>) v).getText());
                } else {
                    BaseEnum e = BaseEnumUtils.getByCode(enumAt.value(), v);
                    jgen.writeObject(e.getText());
                }
            }
            jgen.writeEndArray();
        }

    }

    private void writeCode(JsonGenerator jgen, Object value) throws IOException {
        jgen.writeFieldName(fieldName + EnumConstant.CODE_FIELD_SUFFIX);
        if (fieldClass.isArray()) {
            jgen.writeStartArray();
            for (Object v : (Object[]) value) {
                if (v instanceof BaseEnum) {
                    jgen.writeObject(((BaseEnum<?>) v).getText());
                } else {
                    BaseEnum e = BaseEnumUtils.getByCode(enumAt.value(), v);
                    jgen.writeObject(e.getCode());
                }

            }
            jgen.writeEndArray();
        }

        if (value instanceof Collection) {
            jgen.writeStartArray();
            for (Object v : (Collection) value) {
                if (v instanceof BaseEnum) {
                    jgen.writeObject(((BaseEnum<?>) v).getText());
                } else {
                    BaseEnum e = BaseEnumUtils.getByCode(enumAt.value(), v);
                    jgen.writeObject(e.getCode());
                }
            }
            jgen.writeEndArray();
        }

    }


    private void writeDefaultEnumArr(JsonGenerator jgen, Object value) throws IOException {
        if (fieldClass.isArray()) {
            jgen.writeStartArray();
            for (Object v : (Object[]) value) {
                if (v instanceof BaseEnum) {
                    BaseEnum e = (BaseEnum) v;
                    jgen.writeObject(e);
                } else {
                    jgen.writeObject(v);
                }
            }
            jgen.writeEndArray();
        }

        if (value instanceof Collection) {
            jgen.writeStartArray();
            for (Object v : (Collection) value) {
                if (v instanceof BaseEnum) {
                    BaseEnum e = (BaseEnum) v;
                    jgen.writeObject(e);
                } else {
                    jgen.writeObject(v);
                }
            }
            jgen.writeEndArray();
        }


    }


    private String getFieldEnumText(EnumField enumAt, Object value) {
        Class<? extends BaseEnum> enumClass = enumAt.value();

        if (StringUtil.isBlank(enumAt.separator())) {
            return BaseEnumUtils.getDisplayName(enumClass, value);
        } else {
            return BaseEnumUtils.getDisplayNames(enumClass, value, enumAt.separator());
        }
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            //为空直接跳过
            return serializerProvider.findNullValueSerializer(beanProperty);
        }


        EnumField enumAt = beanProperty.getAnnotation(EnumField.class);
        if (null == enumAt) {
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }


        return new EnumAtSerializer(beanProperty.getName(), beanProperty.getType().getRawClass(), enumAt);
    }
}